package vip.xumy.admin.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import vip.xumy.admin.um.pojo.User;
import vip.xumy.core.exception.CoreException;
import vip.xumy.core.golbal.GlobalBuffer;
import vip.xumy.core.golbal.GlobalConstant;
import vip.xumy.core.pojo.com.Cache;
import vip.xumy.core.utils.StringUtil;

/**	Ownership belongs to the company
 *	author:mengyxu
 *	date:2019年5月27日
 */

public class LoginUtil {
	public static Integer timeout;
	public static String domain;
	
	private static String getTokenKey(String userId) {
		return GlobalConstant.TIKEN_KEY_PREFIX+userId;
	}
	
	public static boolean isLogin(String userId) {
		Cache cache = GlobalBuffer.getCache(getTokenKey(userId));
		return !Cache.isEmpty(cache);
	}
	
	public static void remveLoginInfo(String userId) {
		String tokenKey = LoginUtil.getTokenKey(userId);
		Cache token = GlobalBuffer.getCache(tokenKey);
		if(!Cache.isEmpty(token)){
			String value = token.getValue();
			GlobalBuffer.removeCache(value.substring(0, 10));
			GlobalBuffer.removeCache(tokenKey);
		}
	}
	
	public static void saveLoginInfo(User user, HttpServletRequest request,
			HttpServletResponse response) throws CoreException{
		//删除旧的token信息
		String userId = user.getUserId();
		Cache exitToken = GlobalBuffer.getCache(LoginUtil.getTokenKey(userId));
		if(!Cache.isEmpty(exitToken)){
			String value = exitToken.getValue();
			GlobalBuffer.removeCache(value.substring(0, 10));
		}

		//计算新的token
		String ip = BaseLogUtil.getIpAddr(request);
		String seq = GlobalBuffer.getSeq();
		String token = seq + StringUtil.md5(user.getUserId() + ip + System.currentTimeMillis(), false);
		
		//保存用户token
		GlobalBuffer.addCache(LoginUtil.getTokenKey(userId), new Cache(token, timeout*60));
		//保存token的用户信息
		GlobalBuffer.addCache(seq, new Cache(user, timeout*60));
		//删除验证码
		GlobalBuffer.removeCache(getCodeKey(userId));
		
		LoginUtil.addToken(request, token, response);
		
	}
	
	private static void addToken(HttpServletRequest request, String token, HttpServletResponse response){
		Cookie cookie = new Cookie(GlobalConstant.LOGIN_COOKIE_NAME, token);
		if(!StringUtil.isEmpty(domain)) {
			cookie.setDomain(domain);
		}
		cookie.setPath("/");
		response.addCookie(cookie);
	}
	
	public static User getUserInfo(String token, HttpServletRequest request, boolean refresh){
		if(StringUtil.isEmpty(token)){
			token = getToken(request);
		}
		if(StringUtil.isEmpty(token) || token.length() != 42){
			return null;
		}
		Cache userCache = GlobalBuffer.getCache(token.substring(0, 10));
		if(Cache.isEmpty(userCache)){
			return null;
		}
		User user = userCache.getValue();
		String userId = user.getUserId();
		Cache exitToken = GlobalBuffer.getCache(LoginUtil.getTokenKey(userId));
		if(Cache.isEmpty(exitToken)){
			return null;
		}
		if(StringUtil.equals(token, exitToken.getValue())) {
			if(refresh) {
				userCache.refresh();
				exitToken.refresh();
			}
			return user;
		}
		return null;
	}
	
	public static String getUserId(HttpServletRequest request) {
		User user = getUserInfo(null, request, false);
		if(user == null) {
			return null;
		}
		return user.getUserId();
	}
	
	public static String getUserNameAndRefresh(HttpServletRequest request) {
		return getUserInfo(null, request, true).getUserId();
	}
	
	public static User getUserInfo(HttpServletRequest request){
		return getUserInfo(null, request, false);
	}
	
	public static void loginOut(HttpServletRequest request){
		String token = LoginUtil.getToken(request);
		if(!StringUtil.isEmpty(token)){
			String seq = token.substring(0, 10);
			Cache userCache = GlobalBuffer.getCache(seq);
			if(!Cache.isEmpty(userCache)){
				User user = userCache.getValue();
				String userId = user.getUserId();
				GlobalBuffer.removeCache(getTokenKey(userId));
			}
			GlobalBuffer.removeCache(seq);
		}
	}
	
	public static String getToken(HttpServletRequest request){
		Cookie[] cookies = request.getCookies();
		if(cookies == null){
			return null;
		}
		for (Cookie cookie : cookies) {
			if(GlobalConstant.LOGIN_COOKIE_NAME.equals(cookie.getName())){
				return cookie.getValue();
			}
		}
		return null;
	}
	
	public static String getParentContent(HttpServletRequest request) {
		return request.getParameter("content");
//		String refer = request.getHeader("Referer");
//		try {
//			URL url = new URL(refer);
//			String prefix = request.getContextPath() + "/";
//			return url.getPath().replace(prefix, "");
//		} catch (Exception e) {
//			log.error("获取ParentContent失败",e);
//		}
//		return null;
	}

	public static String getCode(String userId) {
		String code = StringUtil.getStringNum(10);
		GlobalBuffer.addCache(getCodeKey(userId), new Cache(code, timeout*60));
		return code;
	}
	
	private static String getCodeKey(String userId) {
		return GlobalConstant.CODE_KEY_PREFIX+userId;
	}

	public static boolean checkCode(String userId, String code) {
		if(code == null) {
			return false;
		}
		Cache cache = GlobalBuffer.getCache(getCodeKey(userId));
		if(!Cache.isEmpty(cache) && code.equals(cache.getValue())) {
			return true;
		}
		return false;
	}

}
